package com.saifan.wyy_ov;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.data.bean.RoomInfoBean;
import com.saifan.wyy_ov.data.bean.User;
import com.saifan.wyy_ov.data.bean.VistorLoginBean;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.communitycenter.RoomSelectActivity;
import com.saifan.wyy_ov.ui.guide.GuideActivity;
import com.saifan.wyy_ov.ui.home.MainActivity;
import com.saifan.wyy_ov.ui.set.Company;
import com.saifan.wyy_ov.ui.set.Project;
import com.saifan.wyy_ov.ui.set.ServerSetActivity;

import com.saifan.wyy_ov.ui.user.LoginActivity;
import com.saifan.wyy_ov.utils.ActivitysManager;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ToastUtil;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lomasky.ma.httpUtils.HttpUtil;
import lomasky.ma.httpUtils.ICallBack;
import lomasky.ma.httpUtils.JsonUtil;
import lomasky.ma.httpUtils.ResponseBean;
import lomasky.ma.utils.SharedPrefUtil;


/**
 * @version V1.0.0
 * @author: lomasky
 * @date: 2015-6-19 15:53:48
 * @descrption
 */

public class StartActivity extends AppCompatActivity {


    private Project project;

    @Override
    protected void onStart() {
        super.onStart();
        if (SharedPrefUtil.getBoolean(StartActivity.this, "firstInstall", true)) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    startActivity(new Intent(StartActivity.this, GuideActivity.class));
                    close();
                }
            }, 2000);
            return;
        }
        if (project != null) {
            loadCompanyAndProject();
        } else {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    startActivity(new Intent(StartActivity.this, ServerSetActivity.class));
                    close();
                }
            }, 2000);
        }


    }

    private void loadCompanyAndProject() {
        Map<String, Object> map = new HashMap<>();
        map.put("action", "TBSJ");
        map.put("WYGSLX", 2);//（1思源2赛帆）
        map.put("XMLX", 2);
        HttpUtil.check(this, map, new ICallBack() {
            @Override
            public void err(String e) {
                goServerSet();
            }

            @Override
            public void ok(ResponseBean responseBean) {
                if (responseBean.ok) {
                    List<Company> list = JsonUtil.getList(responseBean.content, Company.class);
                    boolean hasPro = false;
                    for (Company company : list) {
                        if (company.getProject() != null || company.getProject().size() > 0) {
                            for (Project project1 : company.getProject()) {
                                if (project1.getID() == project.getID()) {
                                    hasPro = true;
                                    project.setP_JSSJ(project1.getP_JSSJ());
                                    break;
                                }
                            }
                        }
                    }
                    if (hasPro) {
                        checkPro(project);
                    } else {
                        goServerSet();
                    }

                } else {
                    goServerSet();
                }

            }
        });
    }

    private void startActivity(Class clazz) {
        startActivity(new Intent(this, clazz));
    }


    private void checkPro(Project project) {
        boolean isTest = project.getP_SFQY() != 0;
        if (isTest) {
            String csTime = project.getP_JSSJ();
            if (TextUtils.isEmpty(csTime)) {
                goServerSet();
                return;
            }
            Date date = StringUtil.getYYYYMMDD(csTime);

            if (date != null) {
                if (date.before(new Date())) {
                    goServerSet();
                    return;

                }


            } else {
                goServerSet();
                return;
            }
        }
        loginOrMain();


    }

    private void goServerSet() {
        startActivity(ServerSetActivity.class);


        close();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        project = JsonUtil.getObject(SharedPrefUtil.getString(this, "SelectProject", ""), Project.class);
        setContentView();
        ActivitysManager.getManager().addActivity(this);


    }

    private void loginOrMain() {
        String user = SharedPrefUtil.getString(this, "UserName", "");
        String pwd = SharedPrefUtil.getString(this, "Password", "");
        if (!user.equals("") && !pwd.equals("")) {
            login(user, pwd);
        } else {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
//                    overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                    StartActivity.this.startActivity(new Intent(StartActivity.this, LoginActivity.class));

                }
            }, 2000);
        }


    }

    public void setContentView() {
        setContentView(R.layout.activity_start);
    }


    //登录
    public void login(String user, String pwd) {

        final GetData getData = new GetData();
        getData.getDataJson(this, Api.Customer.LOGIN, new User(user, pwd), getString(R.string.wait), new ResponseData() {
            @Override
            public void onSuccess(String json) {

                List<RoomInfoBean> roomInfoBeans = new Gson().fromJson(json, new TypeToken<List<RoomInfoBean>>() {
                }.getType());

                if (roomInfoBeans != null) {
                    SharedPrefUtil.putString(StartActivity.this, "roomInfos", new Gson().toJson(roomInfoBeans));

                }

                Intent intent;
                if (roomInfoBeans.size() == 1) {


                    if (roomInfoBeans.get(0).getWYKHDA_KHYHM() == null) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(StartActivity.this);
                        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                                startActivity(new Intent(StartActivity.this, LoginActivity.class));

                            }
                        });
                        builder.setTitle("提示");
                        builder.setMessage("您还没在管理处登记电话，请您先到管理处登记,或者使用其它账号");
                        builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
                            @Override
                            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                                switch (keyCode) {
                                    case KeyEvent.KEYCODE_BACK:


                                        break;
                                    default:
                                        break;
                                }
                                return true;
                            }
                        });
                        builder.setCancelable(false);
                        builder.create().show();

                        return;
                    }


                    intent = new Intent(StartActivity.this, MainActivity.class);
                    SharedPrefUtil.putString(StartActivity.this, "roomInfo", new Gson().toJson(roomInfoBeans.get(0)));
                    startActivity(intent);
                    close();

                } else if (roomInfoBeans.size() > 1) {
//                    String WYFJDA_FJMC = SharedPrefUtil.getString(StartActivity.this, "WYFJDA_FJMC", "");
//                    if (WYFJDA_FJMC.equals("")) {
//                        intent = new Intent(StartActivity.this, RoomSelectActivity.class);
//
//                    } else {
//                        for (RoomInfoBean roomInfoBean : roomInfoBeans) {
//                            if (roomInfoBean.getWYFJDA_FJMC().equals(WYFJDA_FJMC)) {
//                                SharedPrefUtil.putString(StartActivity.this, "roomInfo", new Gson().toJson(roomInfoBean));
//                                SharedPrefUtil.putString(StartActivity.this, "WYFJDA_FJMC", roomInfoBean.getWYFJDA_FJMC());
//                                break;
//                            }
//                        }
//                        intent = new Intent(StartActivity.this, MainActivity.class);
//                    }
                    intent = new Intent(StartActivity.this, RoomSelectActivity.class);
                    intent.putExtra("must", true);
                    startActivity(intent);
                    close();
                }


            }

            @Override
            public void onFailed(String str) {
                Intent intent = new Intent(StartActivity.this, LoginActivity.class);
                startActivity(intent);
                close();
            }
        });
    }

    public void showDialog(String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

            }
        });
        builder.setTitle("提示");
        builder.setMessage(msg);
        builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                switch (keyCode) {
                    case KeyEvent.KEYCODE_BACK:
                        dialog.dismiss();

                        break;
                    default:
                        break;
                }
                return true;
            }
        });

        builder.setCancelable(false);
        builder.create().show();
    }

    public void close() {
        ActivitysManager.getManager().removeActivity(this);
    }

}
